﻿using System;
using System.Reflection;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using NLog;

namespace Auth.SqlSugar.IocManager
{
    public class IocManager
    {
        private static IContainer _container;
        public static IContainer InitAutofac(IServiceCollection services)
        {
            var builder = new ContainerBuilder();
            if (services != null)
            {
                builder.Populate(services);
            }
            //注册Repository
            builder.RegisterAssemblyTypes(GetAssemblyByName("Auth.SqlSugar")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(GetAssemblyByName("Auth.Repository")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();
            //注册Service
            builder.RegisterAssemblyTypes(GetAssemblyByName("Auth.Application")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
            
            
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).PropertiesAutowired();

            builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>();
            _container = builder.Build();
            return _container;

        }  
        /// <summary>
        /// 根据程序集名称获取程序集
        /// </summary>
        /// <param name="assemblyName">程序集名称</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(String assemblyName)
        {
            return Assembly.Load(assemblyName);
        }

        /// <summary>
        /// 从容器中获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static T Resolve<T>()
        {
            return _container.Resolve<T>();
        }
    }
}